using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Ras2ClassLib;

namespace Ras2
{
	public enum SongColumns
	{
		colName = 0,
		colDescription = 1,
		NumberOfColumns = 2
	}

	public partial class m_viewSongs : UserControl
	{
		private SortOrder[] m_arrLastSortOrder = new SortOrder[(int)ListColumns.NumberOfColumns];
		private LagDoc m_document;

		public LagDoc Document
		{
			get { return m_document; }
			set { m_document = value; }
		}

		public m_viewSongs()
		{
			InitializeComponent();
		}

		private void OnLoadSong(object sender, EventArgs e)
		{
			if (!this.DesignMode)
			{
				m_listViewSongs.Items.Clear();
				LagDoc doc = new LagDoc();
				LagCollection songs = doc.GetAllLag();

				foreach (Lag song in songs)
				{
					m_listViewSongs.Items.Add(GetListViewItem(song));
				}
			}
		}

		private void OnDoubleClickSong(object sender, EventArgs e)
		{
			Update();
		}

		private void OnSortSong(object sender, ColumnClickEventArgs e)
		{
			SortOrder lastOrder = m_arrLastSortOrder[e.Column];
			m_arrLastSortOrder[e.Column] = (lastOrder == SortOrder.Ascending) ? SortOrder.Descending : SortOrder.Ascending;
			m_listViewSongs.ListViewItemSorter = new SongSorter((SongColumns)e.Column, lastOrder);
		}

		private ListViewItem GetListViewItem(Lag song)
		{
			ListViewItem item = new ListViewItem(song.Name);

			item.SubItems.Add(song.Description);

			item.ImageIndex = 0;

			item.Tag = song;

			return item;
		}

		protected void HandleError(Exception ex)
		{
			MessageBox.Show("Eftirfarandi villa kom upp: \n\n" + ex.Message);
		}

		private void OnViewSong(object sender, EventArgs e)
		{
			Update();
		}

		private void Update()
		{
			try
			{
				if (m_listViewSongs.SelectedItems.Count == 1)
				{
					ListViewItem listViewItem = m_listViewSongs.SelectedItems[0];

					Lag song = (Lag)listViewItem.Tag;

					using (SongDlg dlg = new SongDlg())
					{
						dlg.Song = song;

						if (dlg.ShowDialog() == DialogResult.OK)
						{
							song = dlg.Song;

							Document.UpdateLag(song);    

							int nIndex = listViewItem.Index;
		
							m_listViewSongs.Items.Remove(listViewItem);
							m_listViewSongs.Items.Insert(nIndex, GetListViewItem(song));
						}
					}
				}
			}
			catch (Exception ex)
			{
				HandleError(ex);
			}
		}
		
		private void OnSongUpdate(object sender, EventArgs e)
		{
			Update();
		}

	}
}
